import Vue from "vue";
import VueRouter from "vue-router";
import { MessageBox } from "element-ui";
import { hasToken } from "@/utils/cookie.js";
import store from '@/store'
Vue.use(VueRouter);

const routes = [
  {
    //默认进入登录界面
    path: "/",
    redirect: "login",
  },
  {
    path: "/login",
    name: "login",
    component: () => import("@/views/Login.vue"),
  },
  {
    path: "/home",
    name: "home",
    component: () => import("@/views/Home.vue"),

    children: [
      {
        path: "",
        redirect: "index",
      },
      {
        path: "index",
        name: "index",
        component: () => import("@/views/child/Index.vue"),
      },
      {
        path: "cars",
        name: "cars",
        component: () => import("@/views/child/Cars.vue"),
      },
      {
        path: "info",
        name: "info",
        component: () => import("@/views/child/Info.vue"),
      },
      {
        path: "manage",
        name: "manage",
        component: () => import("@/views/child/Manage.vue"),
      },
      {
        path: "parking",
        name: "parking",
        component: () => import("@/views/child/Parking.vue"),
      },
      {
        path: "person",
        name: "person",
        component: () => import("@/views/child/Person.vue"),
      },
    ],
  },
];

const router = new VueRouter({
  routes,
});

//白名单：不需要登录就可以直接通行的页面:登录页
const whitePageList = ["/login"];

router.beforeEach((to, from, next) => {
  //判断是否有登录，通过是否存有token来判断
  if (hasToken()) {
    //有登录，放行
    store.dispatch("getPlotData")
    next();
  }
  //未登录的话，提示要登录
  else {
    if (whitePageList.includes(to.path)) {
      next();
    } else {
      MessageBox.confirm("您未登录，请先登录！", "提示", {
        type: "warning",
      })
        .then(() => {
          //点击确定的
          next("/login");
        })
        .catch(() => {
          //点击取消的
          next("/login");
        });
    }
  }
});
export default router;
